<?php

namespace Biz\Services\Site;

use Lumen\Logger\Logger;
use Illuminate\Http\Request;
use Biz\Models\Site\SitePage;
use Biz\Libraries\TranslationUtil;
use Illuminate\Support\Facades\DB;
use Biz\Constants\Site\SitePageConstants;
use Biz\Criteria\Site\CodeFilterCriterion;
use Biz\Criteria\Site\SiteFilterCriterion;
use Biz\Criteria\Site\LocaleFilterCriterion;
use Lumen\Core\Exceptions\BusinessException;
use Biz\Repositories\Site\SitePageRepository;
use Illuminate\Contracts\Pagination\Paginator;

/**
 * SitePageService.
 *
 * @license [http://www.85do.com] [杭州永奥网络科技有限公司]
 * @copyright Copyright (c) 2018-2026 Hangzhou Yongao Technology Co., Ltd. All rights reserved.
 */
class SitePageService
{
    /**
     * @var \Lumen\Repository\Contracts\RepositoryContract
     */
    protected $repository;

    /**
     * RepositoryController constructor.
     *
     * @param SitePageRepository $repository
     */
    public function __construct(SitePageRepository $repository)
    {
        $this->repository              = $repository;
    }

    /**
     * 列表页.
     *
     * @param Request $request
     *
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|mixed
     */
    public function index(Request $request): Paginator
    {
        $site_id  = $request->get('site_id');
        $pageSize = $request->get('page_size', 10);

        $results = $this->repository
            ->with(['translations'])
            ->setCacheLifetime(0)
            ->pushCriterion(new SiteFilterCriterion($site_id))
            //->pushCriterion(new LocaleFilterCriterion())
            ->paginate($pageSize);

        return $results;
    }

    /**
     * Find.
     *
     * @param int $id
     *
     * @throws BusinessException
     *
     * @return SitePage
     */
    public function find(int $id): SitePage
    {
        $page = $this->repository->find($id);
        if (is_null($page)) {
            throw new BusinessException(trans('site.page_not_found'));
        }

        return $page;
    }

    /**
     * Find By uid.
     *
     * @param string $uid
     *
     * @throws BusinessException
     *
     * @return SitePage
     */
    public function findByUid(string $uid): SitePage
    {
        $id   = SitePage::decodeUid($uid);

        return $this->find($id);
    }

    /**
     * With find.
     *
     * @param int   $id
     * @param array $with
     *
     * @throws BusinessException
     *
     * @return SitePage
     */
    public function findWith(int $id, $with = []): SitePage
    {
        $site = $this->repository->with($with)->find($id);
        if (is_null($site)) {
            throw new BusinessException(trans('site.page_not_found'));
        }

        return $site;
    }

    /**
     * Find By Site Id.
     *
     * @param int $site_id
     *
     * @throws BusinessException
     *
     * @return bool
     */
    public function findBySiteId(int $site_id)
    {
        $page = $this->repository
            ->pushCriterion(new SiteFilterCriterion($site_id))
            ->findFirst();

        return $page;
    }

    /**
     * Find By Site Id.
     *
     * @param string $code
     *
     * @throws BusinessException
     *
     * @return bool
     */
    public function findByCode(string $code)
    {
        $page = $this->repository
            ->setCacheLifetime(0)
            ->pushCriterion(new CodeFilterCriterion($code))
            ->findFirst();

        return $page;
    }

    /**
     * Create.
     *
     * @param array $data
     *
     * @throws \Exception
     *
     * @return SitePage
     */
    public function create(array $data): SitePage
    {
        // 1) Start Transaction
        DB::beginTransaction();
        try {
            // 创建介绍
            $data['status'] = SitePageConstants::STATUS_NORMAL;

            $data = TranslationUtil::convertTranslationsData($data);

            $page   = $this->repository->create($data);
            if (! $page) {
                throw new BusinessException(trans('site.page_create_fail'));
            }
            // Load Translations
            $page->load('translations');

            // 2) Commit Transaction
            DB::commit();
        } catch (\Exception $e) {
            // 3) Rollback Transaction
            DB::rollback();
            // 4) Log Transaction
            Logger::error(__CLASS__, __FUNCTION__, $e);
            // 5) Throw Exception
            throw $e;
        }

        return $page;
    }

    /**
     * Detail.
     *
     * @param string $id
     *
     * @throws BusinessException
     *
     * @return SitePage
     */
    public function show(string $id): SitePage
    {
        $id   = SitePage::decodeUid($id);
        $site = $this->findWith($id, ['translations']);

        return $site;
    }

    /**
     * Edit.
     *
     * @param string $id
     * @param array  $data
     *
     * @throws \Exception
     *
     * @return SitePage
     */
    public function edit(string $id, array $data): SitePage
    {
        $id   = SitePage::decodeUid($id);

        return $this->update($id, $data);
    }

    /**
     * Update.
     *
     * @param int   $id
     * @param array $data
     *
     * @throws \Exception
     *
     * @return SitePage
     */
    public function update(int $id, array $data): SitePage
    {
        $page = $this->find($id);

        // 1) Start Transaction
        DB::beginTransaction();
        try {
            $data = TranslationUtil::convertTranslationsData($data);

            $page   = $this->repository->update($page, $data);
            if (! $page) {
                throw new BusinessException(trans('site.page_create_fail'));
            }

            // 2) Commit Transaction
            DB::commit();
        } catch (\Exception $e) {
            // 3) Rollback Transaction
            DB::rollback();
            // 4) Log Transaction
            Logger::error(__CLASS__, __FUNCTION__, $e);
            // 5) Throw Exception
            throw $e;
        }

        return $page;
    }

    /**
     * Remove.
     *
     * @param string $id
     *
     * @throws \Exception
     *
     * @return bool
     */
    public function remove(string $id): bool
    {
        $id   = SitePage::decodeUid($id);

        return $this->delete($id);
    }

    /**
     * Delete.
     *
     * @param int $id
     *
     * @throws \Exception
     *
     * @return bool
     */
    public function delete(int $id): bool
    {
        /** @var SitePage $page */
        $page = $this->find($id);

        // 1) Start Transaction
        DB::beginTransaction();
        try {
            $this->repository->delete($page);

            // 2) Commit Transaction
            DB::commit();
        } catch (\Exception $e) {
            // 3) Rollback Transaction
            DB::rollback();
            // 4) Log Transaction
            Logger::error(__CLASS__, __FUNCTION__, $e);
            // 5) Throw Exception
            throw $e;
        }

        return true;
    }
}
